package com.github.binarywang.demo.wx.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.demo.wx.mp.utils.HttpUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/wx/token")
public class WxTokenController {
    private final WxMpService wxService;
    private final WxMpMessageRouter messageRouter;

    @GetMapping("/getToken")
    public String getToken() throws Exception {
        String url = " https://api.weixin.qq.com/cgi-bin/token";
        String appId = "wx83c7277bbc6d7a9e";
        String appSecret = "e7601539a62a2abfcaf4457e05d9621e";
        Map<String, String> params = new HashMap<String, String>();

        params.put("grant_type", "client_credential");
        params.put("appid", appId);
        params.put("secret", appSecret);

        String json = HttpUtils.sendGet(url, params);
        String access_token = JSONObject.parseObject(json).getString("access_token");

        System.out.println(LocalDateTime.now() + "token为==============================" + access_token);
        return  access_token;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

}
